import 'dart:convert';

import 'package:atlas/config/apiConfig.dart';
import 'package:atlas/util/ApiUri.dart';
import 'package:http/http.dart';

import '../model/FilmModel.dart';

class HttpService {
  /*获取全部视频列表*/
  Future<List<FilmModel>?> getAllFilm(String page) async {
    String filmApi = "/uyapi/vedio_list.php";
    /* 参数 */
    final params = {
      "keeper": ApiConfig.KEEPER,
      "api": ApiConfig.APPID,
      "page": page,
    };
    Response response = await post(ApiUri().apiUri(filmApi), body: params);
    if (response.statusCode == 200) {
      if (jsonDecode(response.body)['code'] == 'true') {
        final List result = jsonDecode(response.body)['listdata'];
        return result.map((e) => FilmModel.fromJson(e)).toList();
      } else {
        return null;
      }
    } else {
      /* 失败 */
      throw Exception(response.reasonPhrase);
    }
  }

  /*解析*/
  Future<String> getVideoUrl(String id) async {
    String apiUrl = "/uyapi/vedio_play.php";
    /* 请求体 */
    final params = {
      "keeper": ApiConfig.KEEPER,
      "api": ApiConfig.APPID,
      "user": ApiConfig.USER,
      "pass": ApiConfig.PASS,
      "id": id,
    };
    /* 发送 POST 请求 */
    Response response = await post(ApiUri().apiUri(apiUrl), body: params);

    if (response.statusCode == 200) {
      final responseData = json.decode(response.body);
      /* 从 JSON 数据中获取视频的 URL */
      String videoUrl = responseData['playurl'];
      return videoUrl;
    } else {
      throw Exception('Failed to fetch video URL');
    }
  }

  /*获取文档*/
  Future<String> getFile(String key) async {
    String filmApi = "/uyapi/file_text.php";
    /* 参数 */
    final params = {
      "keeper": ApiConfig.KEEPER,
      "api": ApiConfig.APPID,
      "title": "data",
    };
    Response response = await post(ApiUri().apiUri(filmApi), body: params);
    if (response.statusCode == 200) {
      final responseData = json.decode(response.body);
      return responseData[key];
    } else {
      throw Exception('Failed to fetch video URL');
    }
  }
}
